//
//  ImgFileController.m
//  gdemm
//
//  Created by 乔明超 on 16/10/9.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "ImgFileController.h"
#import "UserDefaultsUtil.h"
#import "SVProgressHUD.h"
#define DEVICEVERSION     [[[UIDevice currentDevice] systemVersion] floatValue]
@interface ImgFileController ()<UIGestureRecognizerDelegate,WKNavigationDelegate>

@end

@implementation ImgFileController
- (UIWebView *)webView{
    if (_webView == nil) {
        _webView = [[UIWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _webView.scalesPageToFit = YES;
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:nil];
        longPress.delegate = self; 
        
        longPress.minimumPressDuration = 0.4;
        
        [_webView addGestureRecognizer:longPress];
        [self.view addSubview:_webView];
    }
    return _webView;
}
- (WKWebView *)WKwebView{
    if (_WKwebView == nil) {
        _WKwebView = [[WKWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:nil];
         _WKwebView.navigationDelegate = self;
        longPress.delegate = self; //记得在.h文件里加上委托
        
        longPress.minimumPressDuration = 0.4;
        
        [_WKwebView addGestureRecognizer:longPress];
        [self.view addSubview:_WKwebView];
    }
    return _WKwebView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    if ([DeviceTypeJudge isPadDeviceType]) {
        button.frame = CGRectMake(0, 0, 20, 20);
    }else{
        button.frame = CGRectMake(0, 0, 16, 16);
    }
    
    [button setImage:[[UIImage imageNamed:@"navigationBar_back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(leftButtonPopHandler) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = leftButton;
    self.navigationItem.title = NSLocalizedString(@"str_cloud_disk",  @"云盘");
    // Do any additional setup after loading the view.
    //判断是否打开了水印策略，添加水印效果
    if ([[UserDefaultsUtil shareInstance] getBool:LC_OPENWATERMARKPOLICY]) {
        for (int i = 0; i < 3; i++) {
            UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(20, i * (WINDOWHEIGHT - 200)/2, 250, 80)];
            label.font = [UIFont systemFontOfSize:16];
            label.textColor = [UIColor grayColor];
            label.transform = CGAffineTransformMakeRotation(-M_1_PI);
            label.text =  [[UserDefaultsUtil shareInstance]getString:LC_WATRMARKTEXT];
            if (DEVICEVERSION <= 8.0) {
                [self.webView addSubview:label];
            }else{
                [self.WKwebView addSubview:label];
            }
        }
    }
    [self showFile];
}
-(void)leftButtonPopHandler{
    [self.navigationController popViewControllerAnimated:YES];
}




- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillAppear:animated];
    [SVProgressHUD dismiss];
}
- (void) showFile
{
    if (self.path)
    {
        NSURL* url = [NSURL fileURLWithPath:self.path];
        if (url != nil)
        {
           //判断gif图
            NSArray * subArray = [self.path componentsSeparatedByString:@"."];
            NSString * suffixStr = subArray.lastObject;
            if ([suffixStr caseInsensitiveCompare:@"gif"] == NSOrderedSame) {
                NSData *gifData = [NSData dataWithContentsOfFile:self.path];
                if (DEVICEVERSION <= 8.0) {
                      [self.webView loadData:gifData MIMEType:@"image/gif" textEncodingName:@"UTF-8" baseURL:nil];
                }else{
                      [self.WKwebView loadData:gifData MIMEType:@"image/gif" characterEncodingName:@"UTF-8" baseURL:nil];
                }
            }else{
                
                if (DEVICEVERSION <= 8.0) {
                    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
                }else{
                    [self.WKwebView loadFileURL:url allowingReadAccessToURL:url];
                }
            }

        }
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer

{
    return NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark-WKWebView的代理方法
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD showWithStatus:NSLocalizedString(@"str_pleaseWaitForTheFileLoaded...", @"请等待文件加载完成...")];
    
}
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [SVProgressHUD dismiss];
}
#pragma mark webView的代理方法

- (void)webViewDidStartLoad:(UIWebView *)webView{
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD showWithStatus:NSLocalizedString(@"str_pleaseWaitForTheFileLoaded...", @"请等待文件加载完成...")];
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [SVProgressHUD dismiss];
}


-(void)dealloc{
    if (DEVICEVERSION <= 8.0) {
        [[NSURLCache sharedURLCache] removeAllCachedResponses];//清除缓存
    }else{
        [self removeWKWebViewCache];
//        self.WKwebView.navigationDelegate = nil;
//        [self.WKwebView removeFromSuperview];
    }
    
    
}
-(void)removeWKWebViewCache{
    NSSet *websiteDataTypes = [NSSet setWithArray:@[
                                                    WKWebsiteDataTypeDiskCache,
                                                    WKWebsiteDataTypeOfflineWebApplicationCache,
                                                    WKWebsiteDataTypeMemoryCache,
                                                    WKWebsiteDataTypeLocalStorage,
                                                    WKWebsiteDataTypeCookies,
                                                    WKWebsiteDataTypeSessionStorage,
                                                    WKWebsiteDataTypeIndexedDBDatabases,
                                                    WKWebsiteDataTypeWebSQLDatabases
                                                    ]];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes
                                               modifiedSince:dateFrom completionHandler:^{
                                                   
                                               }];
}

@end
